﻿/* $RCSFile: ProductOptions.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice.ECommerce/PageModules/ProductOptions/ProductOptions.ascx.cs $
 * $log$
 * Revision 21 2010/08/09 11:08:12  christian.surieux
 *   Added Log comment to all .ascx .aspx .master files
 * Revision 8 2010/08/09 10:07:05  christian.surieux
 *   Added Log comment to all cs files
 */

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;  
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Data.SqlClient;
using System.Web.Services.Protocols;
using System.IO;
using System.ComponentModel;
using System.Globalization;

using AddonNice.Core;
using AddonNice.UI;
using AddonNice.Design;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Settings;

using AddonNice.CRMWrapper;
using CrmSdk;
using AddonNice.CRMImage.UI;
using AddonNice.ECommerce;
using AddonNice.ECommerce.UI.WebControls;
using AddonNice.CRMWrapper.ECommerce;
using AddonNice.Settings.ECommerce;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;
using Path2     =   AddonNice.Settings.Path;


namespace AddonNice.PageModules.ProductOptions
{
 	#region Local TraceSwitch 
	public class ProductOptionsTrace : ADNTraceSwitch
	{
		static public ADNTraceSwitch	Sw	=	new ADNTraceSwitch("ProductOptionsTrace","Special Trace Switch for ProductOptions");
	}
	#endregion Local TraceSwitch 

    public partial class ProductOptions : ECommerceModule
    {
        
        #region Global implementation

		/// <summary>
		/// Only 4
		/// </summary>
		public override VersionType ModuleType
		{
			get
			{
				return VersionType.CrmV3|VersionType.CrmV4;
			}
		}

        public override bool AdminModule
        {
            get
            {
                return false;
            }
        }

        public override Guid GuidID
        {
            get
            {
                return  new Guid(EComStStr.ProductOptionsGuid);
            }
        }

        public override bool DependsFromCustomCrmEntities
        {
            get{ return true;}
        }
        
        /// <summary>
        /// SortedList of entities/version from which this module depends, schema name is the key, version is a string in the form major.minor
        /// </summary>
        public override SortedList<string,string> RelatedCustomEntities
        {
            get
            {
                SortedList<string,string> Lst =   new SortedList<string,string>();
                Lst.Add(CrmStr.product,"1.0");
                return Lst;
            }
        }

		#endregion Global Implementation

        #region properties

		protected ImageMetaData	Metadata    =   new ImageMetaData();


		string _MetadataXml                 =   string.Empty;
		protected string MetadataXml
		{
			get 
			{
                if (_MetadataXml == string.Empty)
                {
                    object ob               =   ViewState["MetadataXml"];
                    if (ob == null)
                        return string.Empty;
                    _MetadataXml            =   (string)ob;
                }
				return _MetadataXml; 
			}
			set 
			{ 
				ViewState["MetadataXml"]    =   value; 
                _MetadataXml                =   value;
			}
		}

        
        #endregion properties

        
        public ProductOptions()
        {
            //const string extgrp                 =   "PRODUCTOPTIONS";
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]ProductOptions Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]ProductOptions Ctor END.",ModuleTraceSwitch.Sw.Info);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (ProductOptionsTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ProductOptions Page_Load BEG IsPostBack: {0}, IsUnderCRM: {1}.",IsPostBack,IsUnderCRM),
                    (ProductOptionsTrace.Sw.TraceVerbose)? ProductOptionsTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
            if (!IsPostBack)
            {
			    // After up or down button when the page is refreshed, 
			    // select the previously selected tab from the list.
                if ( IsUnderCRM && !IsInEntityCreationMode && ( RequestEntityTypename == CrmStr.product ) )
			    {
				    try
				    {
                        ADNDynEProduct prod         =   new ProductsCRM().GetProduct(EntityID);
                        if (ProductOptionsTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ProductOptions Page_Load EntityID: {0}",EntityID),ProductOptionsTrace.Sw.Info);
						// metadata only used for image of product
                        MetadataXml                 =   prod.adnmetadataxml;   
                        if (ProductOptionsTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ProductOptions Page_Load MetadataXml: '{0}'.",MetadataXml),ProductOptionsTrace.Sw.Info);
                        Metadata.LoadXml(MetadataXml);
                        string productOptions       =   Metadata.GetElement(EComStStr.ProductOptions,true).OuterXml;
                        ctlOptions1.OptionString    =   productOptions;
                        ctlOptions2.OptionString    =   productOptions;
                        ctlOptions3.OptionString    =   productOptions;
                        ctlOptions4.OptionString    =   productOptions;
				    }
				    catch(Exception ex)
				    {
		                if (ModuleTraceSwitch.Sw.TraceError)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ProductOptions Page_Load ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                        throw;
				    }
			    }
            }
			else
			{
				if ( MetadataXml != string.Empty )
					Metadata.LoadXml(MetadataXml);
			}			
        }
        
        /// <summary>
        /// Update the product and insert result in crm form field adn_metadatxml
        /// </summary>
        void ProductOptions_ADNUpdateModule(object sender, ModuleEventArgs e)
        {
            if (ProductOptionsTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ProductOptions ProductOptions_ADNUpdateModule BEG OptionString: '{0}'.",ctlOptions1.OptionString),
                    (ProductOptionsTrace.Sw.TraceVerbose)? ProductOptionsTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
		    try
		    {
                if (ProductOptionsTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ProductOptions ProductOptions_ADNUpdateModule before insert Metadata.OuterXml: '{0}'",Metadata.OuterXml),ProductOptionsTrace.Sw.Info);
                Metadata.MergeElement(EComStStr.ProductOptions,ctlOptions1.ExtractResultXmlString(),true);
                Metadata.MergeElement(EComStStr.ProductOptions,ctlOptions2.ExtractResultXmlString(),false);
                Metadata.MergeElement(EComStStr.ProductOptions,ctlOptions3.ExtractResultXmlString(),false);
                Metadata.MergeElement(EComStStr.ProductOptions,ctlOptions4.ExtractResultXmlString(),false);
                if (ProductOptionsTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ProductOptions ProductOptions_ADNUpdateModule after insert Metadata.OuterXml: '{0}'",Metadata.OuterXml),ProductOptionsTrace.Sw.Info);
                ADNDynEProduct prod     =   new ProductsCRM().GetProduct(EntityID);
                if ( prod != null )
                {
                    // metadata only used for image of product
                    prod.adnmetadataxml =   Metadata.OuterXml;
                    prod.Update();
                }
		    }
		    catch(Exception ex)
		    {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ProductOptions ProductOptions_ADNUpdateModule ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                throw;
		    }
            if (ProductOptionsTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]ProductOptions ProductOptions_ADNUpdateModule END.",
                    (ProductOptionsTrace.Sw.TraceVerbose)? ProductOptionsTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
        }

        #region Std Control override

        public override void Page_PreInit(object sender, EventArgs e)
        {
             if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]ProductOptions Page_PreInit BEG.",ModuleTraceSwitch.Sw.Info);
            base.Page_PreInit(sender, e);
            string strcult      =   Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
            updateBtn.SkinID    =   "Update_" + strcult;
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]ProductOptions Page_PreInit END.",ModuleTraceSwitch.Sw.Info);
        }

        override protected void OnInit(EventArgs e)
        {
             if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]ProductOptions OnInit BEG.",ModuleTraceSwitch.Sw.Info);
            InitializeComponent();
            base.OnInit(e);
             if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]ProductOptions OnInit END.",ModuleTraceSwitch.Sw.Info);
        }
        
        private void InitializeComponent()
        {
            Load                        +=  new EventHandler(Page_Load);
            ADNUpdateModule             +=  new PortalModuleEventHandler(ProductOptions_ADNUpdateModule);
        }

        #endregion Std Control override

     }
}